package com.czk.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.czk.common.utils.R;
import com.czk.gulimall.cart.feign.ProductFeignService;
import com.czk.gulimall.cart.interceptor.CartInterceptor;
import com.czk.gulimall.cart.service.CartService;
import com.czk.gulimall.cart.vo.Cart;
import com.czk.gulimall.cart.vo.CartItem;
import com.czk.gulimall.cart.vo.SkuInfoVo;
import com.czk.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/3/14 21:20
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    private static final String CART_PREFIX = "gulimall:cart";

    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        // 查找该商品
        String o = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(o)) {
            // 购物车无此商品
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> skuInfo = CompletableFuture.runAsync(() -> {
                // 远程查询要添加的商品信息
                R r = productFeignService.skuInfo(skuId);
                JSONObject jsonObject = (JSONObject) r.getData("data", new TypeReference<Object>() {
                });
                // 转为实体类
                SkuInfoVo skuInfoVo = jsonObject.toJavaObject(SkuInfoVo.class);
                // 商品添加到购物车
                // 选中
                cartItem.setCheck(true);
                // 数量
                cartItem.setCount(num);
                // 图片地址
                cartItem.setImage(skuInfoVo.getSkuDefaultImg());
                // 价格
                cartItem.setPrice(skuInfoVo.getPrice());
                cartItem.setSkuId(skuId);
            }, threadPoolExecutor);
            // 销售属性组合信息
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, threadPoolExecutor);

            // 传递商品id和商品信息
            try {
                CompletableFuture.allOf(skuInfo, voidCompletableFuture).get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            String jsonString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), jsonString);

            return cartItem;
        } else {
            // 购物车有次商品，修改数量
            CartItem cartItem = JSON.parseObject(o, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            // 更新redis
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }

    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String o = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() {

        Cart cart = new Cart();
        // 区分登录还是未登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            // 登录
            String carKey = CART_PREFIX + userInfoTo.getUserId();
            // 如果有临时购物车，进行合并
            // 获取临时购物车数据
            List<CartItem> tempCartItems = getCartItems(CART_PREFIX + userInfoTo.getUserKey());
            if (tempCartItems != null && tempCartItems.size() > 0) {
                // 需要合并
                for (CartItem tempCartItem : tempCartItems) {
                    // 重新添加合并
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                // 清除临时购物车数据
                clearCart(CART_PREFIX + userInfoTo.getUserKey());
            }
            // 获取所有购物车数据
            // 包括临时和登录后的
            List<CartItem> cartItems = getCartItems(carKey);
            cart.setItems(cartItems);
            return cart;
        } else {
            // 未登录
            String userKey = userInfoTo.getUserKey();
            String cartKey = CART_PREFIX + userKey;
            // 拿到所有购物项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
            return cart;
        }
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    private List<CartItem> getCartItems(String cartKey) {
        // 拿到hash操作器
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        // 拿到所有购物项
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(obj -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return new ArrayList<>();
    }

    /**
     * 获取要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 得到用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            // 登录了
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            // 没登录
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        // 绑定hash操作
        // 下面对redis的操作都是对这个key的操作
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        // 获取购物项
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String string = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), string);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSONObject.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo == null) {
            return null;
        }
        String cartKey = CART_PREFIX + userInfoTo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);
        List<CartItem> collect = cartItems.stream().filter(x -> x.getCheck()).map(item -> {
            R price = productFeignService.getPrice(item.getSkuId());
            String data=(String) price.get("data");
            // 获取最新价格
            item.setPrice(new BigDecimal(data));
            return item;
        }).collect(Collectors.toList());

        return collect;

    }
}
